import './login.css'

import { Button, Form, Input, Space, message } from 'antd'
import { checkRecaptcha, login } from '@/api'
import { setAccessToken, setRefershToken } from '@/api'

import type { LoginForm } from '@/types/index'
import Recaptcha from '@/components/ReCAPTCHA ' // 导入 Recaptcha 组件
import SvgIcon from '@/components/SvgIcon'
import { setMenus } from '@/store/modules/front'
import { useAppDispatch } from '@/store/hooks'
import { useNavigate } from 'react-router-dom'
import { useState } from 'react'

const layout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
}

const Login: React.FC = () => {
  const dispatch = useAppDispatch()
  const [messageApi, contextHolder] = message.useMessage() //全局提示信息
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [recaptchaSuccess, setRecaptchaSuccess] = useState(false)
  // 登录
  const handleLogin = async (values: LoginForm) => {
    if (!recaptchaSuccess) {
      return
    }
    const { code, msg, accessToken, refreshToken, MenuList } =
      await login(values)
    if (code === 200) {
      setAccessToken(accessToken)
      setRefershToken(refreshToken)
      localStorage.setItem('showIntro', 'true')
      // 获取用户信息
      dispatch(setMenus(MenuList))
      messageApi.open({
        type: 'success',
        content: msg
      })
      setTimeout(() => {
        navigate('/')
      }, 500)
    } else {
      messageApi.open({
        type: 'error',
        content: msg
      })
    }
  }
  // 重置密码
  const onReset = () => {
    navigate('/reset')
  }

  // 注册
  const toRegister = () => {
    navigate('/register')
  }

  // 行为验证
  const handleRecaptchaChange = async (token: string) => {
    // 将令牌发送到后端进行验证
    const { success, msg } = await checkRecaptcha(token)
    setRecaptchaSuccess(success)
    if (success) {
      messageApi.open({
        type: 'success',
        content: msg
      })
    } else {
      messageApi.open({
        type: 'warning',
        content: msg
      })
    }
  }

  // 校验手机号
  const checkPhone = (_: any, value: string) => {
    const rep = /^1[1356789]\d{9}$/
    if (!rep.test(value)) {
      return Promise.reject('手机号不合法')
    }
    return Promise.resolve()
  }

  // 检查密码
  const checkPwd = (_: any, value: string) => {
    if (value.length < 8 || value.length > 16) {
      return Promise.reject('密码长度8-16位')
    }
    const reg =
      /^(?=(?:.*[a-zA-Z]){1})(?=(?:.*[0-9]){1}|(?:.*[!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){1}|(?:.*[!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){1})(?:[a-zA-Z0-9!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){8,16}$/

    if (!reg.test(value)) {
      return Promise.reject('密码必须包含数字、字母、特殊符号')
    }
    return Promise.resolve()
  }

  return (
    <div className="login">
      {contextHolder}
      <div className="box"></div>
      <Form
        className="form"
        {...layout}
        form={form}
        name="control-hooks"
        onFinish={handleLogin}
      >
        <Form.Item>
          <div className="div">
            <SvgIcon
              name="shop"
              className=""
              width={50}
              height={50}
              fill="#000"
            />
            <h1>Admin System</h1>
          </div>
        </Form.Item>
        <Form.Item
          validateFirst={true}
          name="phone"
          rules={[
            {
              required: true
            },
            { validator: checkPhone }
          ]}
        >
          <Input placeholder="phone" prefix={<SvgIcon name="user" />} />
        </Form.Item>
        <Form.Item
          validateFirst={true}
          name="password"
          rules={[
            {
              required: true
            },
            { validator: checkPwd }
          ]}
        >
          <Input.Password
            placeholder="password"
            prefix={<SvgIcon name="pwd" />}
          />
        </Form.Item>

        <Form.Item rules={[{ required: true }]}>
          <Recaptcha onChange={handleRecaptchaChange} />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
            <Button type="primary" htmlType="button" onClick={onReset}>
              忘记密码
            </Button>
            <Button type="primary" htmlType="button" onClick={toRegister}>
              注册
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}
export default Login
